package com.innovation.ic.cyz.base.service.cyz.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.cyz.base.mapper.cyz.PcFileMapper;
import com.innovation.ic.cyz.base.mapper.cyz.ProductPropertyMapper;
import com.innovation.ic.cyz.base.mapper.cyz.ProductUniqueMapper;
import com.innovation.ic.cyz.base.model.cyz.ProductUnique;
import com.innovation.ic.cyz.base.pojo.constant.ProductConstants;
import com.innovation.ic.cyz.base.pojo.enums.RedisKeyPrefixEnum;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.pojo.variable.cyz.ps_productunique.PsProdsUniqPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.ps_productunique.PsProductQueryByBrandPartRespPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.ps_property.PsProductPropertyRespPojo;
import com.innovation.ic.cyz.base.service.cyz.ProductUniqueService;
import com.innovation.ic.cyz.base.vo.pve_standard.ps_productsunique.PsPartNumbersQueryByContextVo;
import com.innovation.ic.cyz.base.vo.pve_standard.ps_productsunique.PsProductQueryByIdVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linuo
 * @desc ProductUnique表接口实现类
 * @time 2022年11月1日13:57:05
 */
@Service
//@Transactional
public class ProductUniqueServiceImpl extends ServiceImpl<ProductUniqueMapper, ProductUnique> implements ProductUniqueService {
    @Resource
    private ProductUniqueMapper productUniqueMapper;

    @Resource
    private ProductPropertyMapper productPropertyMapper;

    @Autowired
    protected ServiceHelper serviceHelper;

    @Resource
    private PcFileMapper pcFileMapper;

    /**
     * 清空product_unique表数据
     */
    @Override
    public void truncateProductUnique() {
        productUniqueMapper.truncateProductUnique();
    }

    /**
     * 型号模糊查询
     *
     * @param psPartNumbersQueryByContextVo 型号模糊查询的vo类
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<String>> queryPartNumbersByContext(PsPartNumbersQueryByContextVo psPartNumbersQueryByContextVo) {
        List<String> result = productUniqueMapper.queryPartNumbersByContext(psPartNumbersQueryByContextVo);

        ServiceResult<List<String>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 根据品牌、型号查询器件
     * @param psProductQueryByIdVo 查询条件
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<PsProductQueryByBrandPartRespPojo> queryProductsByBrandPartNumber(PsProductQueryByIdVo psProductQueryByIdVo){
        Map<String, String> map = new HashMap<>();
        map.put(ProductConstants.ID_FIELD, psProductQueryByIdVo.getId());
        PsProductQueryByBrandPartRespPojo result = productUniqueMapper.queryProductByBrandPartNumber(map);
        if (result != null && !Strings.isNullOrEmpty(result.getProductID())) {
            // 根据品牌、型号查询属性信息
            result.setProperties(getProperties(result.getProductID()));

            // 查询附件信息
            result.setFiles(pcFileMapper.selectFilesByProductId(result.getProductID()));
        }

        ServiceResult<PsProductQueryByBrandPartRespPojo> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 根据查询器件选型列表
     *
     * @return
     */
    @Override
    public ServiceResult<List<PsProdsUniqPojo>> getPsPPProductsByUids(String[] uids){
        ServiceResult<List<PsProdsUniqPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(productUniqueMapper.getListByUids(uids));
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 批量插入ProductUnique表数据
     *
     * @param list 需要插入的数据
     * @return 返回插入结果
     */
    @Override
    public ServiceResult<Boolean> batchInsertProductUniquesList(List<ProductUnique> list) throws InterruptedException {
        boolean result = Boolean.FALSE;
        String message = ServiceResult.INSERT_FAIL;
        //this.batchInsertProductUniquesRedis(list);
        List<ProductUnique> insertDataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            insertDataList.add(list.get(i));

            // insertDataList数据够了10000条进行入库处理
            if (insertDataList.size() == 10000) {
                Integer insertCount = productUniqueMapper.insertBatchSomeColumn(insertDataList);
                if (insertCount > 0) {
                    result = Boolean.TRUE;
                    message = ServiceResult.INSERT_SUCCESS;
                    Thread.sleep(200);
                }
                insertDataList = new ArrayList<>();
            } else {
                // 最后一条数据处理完且insertDataList有数据保存到数据库
                if (i == list.size() - 1 && insertDataList.size() > 0) {
                    Integer insertCount = productUniqueMapper.insertBatchSomeColumn(insertDataList);
                    if (insertCount > 0) {
                        result = Boolean.TRUE;
                        message = ServiceResult.INSERT_SUCCESS;
                        Thread.sleep(200);
                    }
                    insertDataList = new ArrayList<>();
                }
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setSuccess(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    @Override
    public Integer total() {
        return this.baseMapper.selectCount(new QueryWrapper<>());
    }

    @Override
    public List<ProductUnique> findByPage(int pageNum, int pageSize) {
        int start = pageNum * pageSize;
        int end = start + pageSize;
        if (start > 0) {
            start += 1;
        }
        return this.baseMapper.findByPage(start, end);
    }

    private void batchInsertProductUniquesRedis(List<ProductUnique> list) {
        String key = RedisKeyPrefixEnum.TABLE.getCode() + ":" + RedisKeyPrefixEnum.TABLE_PRODUCT_UNIQUE.getCode();
        try {
            List<ProductUnique> insertDataList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                insertDataList.add(list.get(i));
                if (i % 10000 == 0 && i != 0) {
                    serviceHelper.getRedisManager().lPushAll(key, insertDataList);
                    this.sleep();
                    insertDataList.clear();
                }
            }
            if (!CollectionUtils.isEmpty(insertDataList)) {
                serviceHelper.getRedisManager().lPushAll(key, insertDataList);
            }
        } catch (Exception e) {

        }

    }

    /**
     * 获取器件参数
     *
     * @param productId 产品id
     * @return 返回查询结果
     */
    private List<PsProductPropertyRespPojo> getProperties(String productId) {

        return productPropertyMapper.selectPropertyByProductId(productId);
    }

    /**
     * 线程处理睡眠
     */
    private void sleep() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            log.error("线程睡眠发生异常", e);
        }
    }


}